package com.morningstar.system.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.morningstar.common.dao.entity.CommonQuery;
import com.morningstar.common.result.Result;
import com.morningstar.system.controller.query.SysLogLoginQuery;
import com.morningstar.system.dao.entity.SysLogLogin;
import com.morningstar.system.service.SysLogLoginService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import static com.morningstar.common.constants.permission.PermissionConstants.DETAIL;
import static com.morningstar.common.constants.permission.PermissionConstants.LIST;

/**
 * 用户登录日志接口
 */
@Slf4j
@RestController
@RequestMapping("/logger/login")
public class SysLogLoginController {
    private static final String PERMISSION = "logger.login";

    private static final String PERMISSION_LIST = PERMISSION + LIST;

    private static final String PERMISSION_DETAIL = PERMISSION + DETAIL;

    @Resource
    private SysLogLoginService logLoginService;

    /**
     * 用户登录日志 列表
     *
     * @param commonQuery 查询条件
     * @return 用户登录日志列表
     */
    @PostMapping("/list")
    @SaCheckPermission(PERMISSION_LIST)
    public Result<IPage<SysLogLogin>> list(@RequestBody CommonQuery<SysLogLogin, SysLogLoginQuery> commonQuery) {
        SysLogLoginQuery query = commonQuery.getQuery();
        LambdaQueryWrapper<SysLogLogin> queryWrapper = new LambdaQueryWrapper<>();
        if (query != null) {
            queryWrapper.like(StringUtils.isNotBlank(query.getLoginName()), SysLogLogin::getLoginName, query.getLoginName());
            queryWrapper.like(StringUtils.isNotBlank(query.getLoginIp()), SysLogLogin::getLoginIp, query.getLoginIp());
            if (CollUtil.isNotEmpty(query.getLoginTime()) && query.getLoginTime().size() == 2) {
                queryWrapper.between(SysLogLogin::getLoginTime, query.getLoginTime().get(0), query.getLoginTime().get(1));
            }
        }
        queryWrapper.orderByDesc(SysLogLogin::getLoginTime);
        queryWrapper.orderByDesc(SysLogLogin::getLogId);
        return Result.successData(logLoginService.page(commonQuery.getPage(), queryWrapper));
    }

    /**
     * 用户登录日志详细 信息
     *
     * @param logId 日志Id
     * @return 用户登录日志详细
     */
    @GetMapping("/detail")
    @SaCheckPermission(PERMISSION_DETAIL)
    public Result<SysLogLogin> detail(@RequestParam("logId") Long logId) {
        return Result.successData(logLoginService.getById(logId));
    }

}
